package com.nk.web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nk.domain.AjaxRes;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormFilter extends FormAuthenticationFilter {
    // 认证成功调用
    protected boolean onLoginSuccess(AuthenticationToken token,
                                     Subject subject,
                                     ServletRequest request,
                                     ServletResponse response) throws Exception {

        System.out.println("登录成功");

        // 返回Jason数据
        response.setCharacterEncoding("utf-8");

        AjaxRes ajaxRes = new AjaxRes();
        ajaxRes.setMessage("登录成功");
        ajaxRes.setSuccess(true);
        response.getWriter().print(new ObjectMapper().writeValueAsString(ajaxRes));
        // 返回false表示不需要执行下一个过滤器
        return false;
    }

    // 认证失败调用
    protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e,
                                     ServletRequest request,
                                     ServletResponse response) {
        System.out.println("登录失败");

        AjaxRes ajaxRes = new AjaxRes();
        ajaxRes.setSuccess(false);
        if (e != null){
            String exceptionName = e.getClass().getName();
            if (exceptionName.equals(UnknownAccountException.class.getName())){
               ajaxRes.setMessage("用户名不存在");
            }else if (exceptionName.equals(IncorrectCredentialsException.class.getName())){
                ajaxRes.setMessage("密码错误");
            }else {
                ajaxRes.setMessage("未知错误");
                e.printStackTrace();
            }
        }

        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print(new ObjectMapper().writeValueAsString(ajaxRes));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }
}
